package com.lenovo.leos.letools.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;

import com.lenovo.leos.letools.exception.NetException;
import com.lenovo.leos.letools.utils.Constants;
import com.lenovo.leos.letools.utils.CookieStore;
import com.lenovo.leos.letools.utils.MyX509TrustManager;

/**
 * @author Administrator
 * 封装Get请求
 */
public class HttpGet {

	private String urlpath;
	private HttpsURLConnection conn;
	private String cookie;
	
	public HttpGet(String urlpath,String cookie) {
		this.urlpath = urlpath;
		this.cookie = cookie;
	}
	
	/**
	 * 执行get请求
	 * @return
	 */
	public ResponseValue doGet() throws NetException{
		MyX509TrustManager.allowAllSSL();
		ResponseValue resVal = new ResponseValue();
		try {
			conn = (HttpsURLConnection) (new URL(urlpath)).openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("Cookie", cookie);
			conn.connect();
			InputStream inputStream = conn.getInputStream();
			resVal.setInputStream(inputStream);
			List<String> cookies = CookieStore.filterCookies(conn.getHeaderFields());
			resVal.setCookies(cookies);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new NetException(Constants.NETEXCEPTION,e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new NetException(Constants.NETEXCEPTION,e.getMessage());
		}
		return resVal;
	}
	
	/**
	 * 关闭连接
	 */
	public void closeConn(){
		if(conn!=null)
			conn.disconnect();
	}
}
